// 轮播图详情页JavaScript

document.addEventListener('DOMContentLoaded', function() {
    // 初始化页面
    initBannerDetails();
    
    // 初始化滚动事件
    initScrollEvents();
    
    // 初始化交互事件
    initInteractionEvents();
    
    // 初始化分享功能
    initShareFeature();
    
    // 处理图片错误
    handleImageErrors();
});

// 初始化详情页
function initBannerDetails() {
    // 获取URL参数
    const urlParams = new URLSearchParams(window.location.search);
    const id = urlParams.get('id');
    const source = urlParams.get('source');
    
    if (id) {
        // 尝试从localStorage获取数据
        let bannerInfo = null;
        try {
            bannerInfo = JSON.parse(localStorage.getItem('currentBanner'));
        } catch (e) {
            console.error('解析轮播图数据失败', e);
        }
        
        if (bannerInfo && bannerInfo.id == id) {
            // 使用localStorage中的数据
            renderBannerDetails(bannerInfo);
        } else {
            // 调用API获取数据
            fetchBannerDetails(id);
        }
    } else {
        // 没有ID参数，显示错误信息
        showError('未找到相关内容');
    }
}

// 从API获取详情数据
function fetchBannerDetails(id) {
    // 显示加载状态
    showLoading(true);
    
    // 模拟API请求
    setTimeout(() => {
        // 根据不同ID返回不同的模拟数据
        let data;
        switch(id) {
            case "1":
                data = {
                    id: 1,
                    title: "2023互联网行业人才趋势分析",
                    description: "深度解读互联网行业最新人才需求与薪资走向",
                    image: "../img/banner1.jpg",
                    publishDate: "2023-05-15",
                    viewCount: 2356,
                    content: [
                        {
                            title: "行业概况",
                            content: "2023年，互联网行业经历了新一轮的结构调整与变革。大厂招聘规模趋于稳定，中小企业和创业公司则展现出更强劲的人才需求。AI、大数据、云服务和信息安全领域成为招聘热点。"
                        },
                        {
                            title: "薪资趋势",
                            content: "薪资增长整体趋缓，但AI、云原生等热门领域的人才依然享有溢价。应届生平均起薪在一线城市达到12K-15K，有竞争力的实习经历可提升20%-30%的起薪空间。"
                        },
                        {
                            title: "求职建议",
                            content: "1. 提升核心技术能力，尤其是AI、云原生等热门方向\n2. 积极参与开源项目，展示实际解决问题的能力\n3. 注重项目经验积累，参与实际业务场景\n4. 培养复合技能，如技术+产品、技术+业务等"
                        }
                    ],
                    relatedInfo: [
                        {
                            title: "最新AI人才市场薪资报告",
                            image: "../img/article1.jpg",
                            date: "3天前",
                            views: 1289
                        },
                        {
                            title: "校招生如何选择互联网公司的技术方向",
                            image: "../img/article2.jpg",
                            date: "5天前",
                            views: 987
                        },
                        {
                            title: "云计算领域就业前景分析",
                            image: "../img/article3.jpg",
                            date: "1周前",
                            views: 765
                        }
                    ]
                };
                break;
            case "2":
                data = {
                    id: 2,
                    title: "名企暑期实习申请指南",
                    description: "BAT、字节等头部企业实习机会及申请攻略",
                    image: "../img/banner2.jpg",
                    publishDate: "2023-05-10",
                    viewCount: 1856,
                    content: [
                        {
                            title: "申请时间表",
                            content: "大多数头部互联网企业暑期实习生招聘在2-4月集中开展，部分企业全年招聘。建议至少提前3个月准备，关注校招官网、内推渠道。"
                        },
                        {
                            title: "简历优化要点",
                            content: "1. 突出与岗位相关的专业技能和实践经验\n2. 量化成果，展示解决问题的能力\n3. 突出优势课程和项目经历\n4. 简历控制在1页以内，重点突出"
                        },
                        {
                            title: "面试准备",
                            content: "技术岗：扎实的基础知识（算法、数据结构、计算机网络等）和编程实践能力\n产品岗：产品分析能力、用户思维和行业洞察力\n设计岗：作品集展示和设计理念阐述\n运营岗：数据分析能力和创意执行力"
                        }
                    ],
                    relatedInfo: [
                        {
                            title: "字节跳动实习面试经验分享",
                            image: "../img/article4.jpg",
                            date: "2天前",
                            views: 2103
                        },
                        {
                            title: "实习转正的五大关键因素",
                            image: "../img/article5.jpg",
                            date: "4天前",
                            views: 1567
                        },
                        {
                            title: "如何在实习期快速成长",
                            image: "../img/article6.jpg",
                            date: "1周前",
                            views: 984
                        }
                    ]
                };
                break;
            case "3":
                data = {
                    id: 3,
                    title: "一页纸简历如何突出核心竞争力",
                    description: "HR眼中的优质简历是什么样？",
                    image: "../img/banner3.jpg",
                    publishDate: "2023-05-12",
                    viewCount: 1654,
                    content: [
                        {
                            title: "简历结构优化",
                            content: "遵循"基本信息-教育背景-实习/项目经验-技能特长"的顺序，突出与目标岗位最相关的内容。HR平均只花8-10秒浏览一份简历，确保最重要的信息能在首屏呈现。"
                        },
                        {
                            title: "内容表达技巧",
                            content: "1. 使用行动导向的语言和量化成果\n2. 避免空洞的形容词，用具体事例说话\n3. 针对不同岗位定制内容，突出匹配点\n4. 使用行业关键词，提高简历辨识度"
                        },
                        {
                            title: "常见错误避免",
                            content: "1. 内容冗长，超过一页\n2. 排版混乱，阅读体验差\n3. 过度美化，忽视内容质量\n4. 经历堆砌，缺乏重点筛选\n5. 技能与目标岗位不匹配"
                        }
                    ],
                    relatedInfo: [
                        {
                            title: "HR揭秘：8秒内让简历脱颖而出的技巧",
                            image: "../img/article7.jpg",
                            date: "3天前",
                            views: 1879
                        },
                        {
                            title: "简历中的项目经验该如何写",
                            image: "../img/article8.jpg",
                            date: "5天前",
                            views: 1234
                        },
                        {
                            title: "应届生简历模板与写作指南",
                            image: "../img/article9.jpg",
                            date: "1周前",
                            views: 987
                        }
                    ]
                };
                break;
            default:
                data = {
                    id: id,
                    title: "职业发展资讯",
                    description: "职业生涯规划与发展指南",
                    image: "../img/banner1.jpg",
                    publishDate: "2023-05-15",
                    viewCount: 1209,
                    content: [
                        {
                            title: "内容概述",
                            content: "本文提供了职业发展的相关指导和建议，帮助你规划职业道路，提升职场竞争力。"
                        },
                        {
                            title: "具体内容",
                            content: "详细内容正在加载中..."
                        }
                    ],
                    relatedInfo: []
                };
        }
        
        // 渲染数据
        renderBannerDetails(data);
        
        // 隐藏加载状态
        showLoading(false);
    }, 800); // 模拟加载时间
}

// 渲染详情页内容
function renderBannerDetails(data) {
    // 设置页面标题
    document.title = data.title + " - 人才职业生涯规划平台";
    document.querySelector('.page-title').textContent = "详情"; // 或者可以设置为不同类型的标题
    
    // 设置封面图
    const bannerImage = document.querySelector('.banner-image');
    if (bannerImage) {
        bannerImage.src = data.image;
        bannerImage.alt = data.title;
    }
    
    // 设置标题和描述
    document.querySelector('.detail-title').textContent = data.title;
    document.querySelector('.detail-description').textContent = data.description;
    
    // 设置发布日期和浏览量
    document.getElementById('publish-date').textContent = data.publishDate;
    document.getElementById('view-count').textContent = data.viewCount;
    
    // 设置内容区域
    const contentSections = document.querySelector('.content-sections');
    contentSections.innerHTML = ""; // 清空现有内容
    
    // 添加内容区块
    if (data.content && data.content.length > 0) {
        data.content.forEach(section => {
            const sectionElem = document.createElement('div');
            sectionElem.className = 'content-section';
            
            // 设置标题
            const titleElem = document.createElement('h2');
            titleElem.className = 'section-title';
            titleElem.textContent = section.title;
            sectionElem.appendChild(titleElem);
            
            // 设置内容
            const contentElem = document.createElement('div');
            contentElem.className = 'section-content';
            // 处理换行符
            const paragraphs = section.content.split('\n');
            paragraphs.forEach(para => {
                const p = document.createElement('p');
                p.textContent = para;
                contentElem.appendChild(p);
            });
            
            sectionElem.appendChild(contentElem);
            contentSections.appendChild(sectionElem);
        });
    }
    
    // 设置相关推荐
    const relatedItems = document.querySelector('.related-items');
    relatedItems.innerHTML = ""; // 清空现有内容
    
    // 添加相关推荐项
    if (data.relatedInfo && data.relatedInfo.length > 0) {
        data.relatedInfo.forEach(item => {
            const itemElem = document.createElement('div');
            itemElem.className = 'related-item';
            
            itemElem.innerHTML = `
                <div class="related-img">
                    <img src="${item.image}" alt="${item.title}">
                </div>
                <div class="related-content">
                    <h3>${item.title}</h3>
                    <div class="related-meta">
                        <span class="date">${item.date}</span>
                        <span class="views"><i class="bi bi-eye"></i> ${item.views}</span>
                    </div>
                </div>
            `;
            
            // 添加点击事件
            itemElem.addEventListener('click', function() {
                // 可以跳转到对应的详情页
                window.location.href = `article-details.html?id=${Date.now()}`;
            });
            
            relatedItems.appendChild(itemElem);
        });
    } else {
        // 没有相关推荐时
        const noRelated = document.createElement('p');
        noRelated.className = 'no-related-info';
        noRelated.textContent = '暂无相关推荐';
        relatedItems.appendChild(noRelated);
    }
    
    // 设置底部按钮文本
    document.querySelector('.primary-button').textContent = getPrimaryButtonText(data.id);
}

// 根据不同类型返回不同的主按钮文本
function getPrimaryButtonText(id) {
    switch(id) {
        case 1:
            return "查看完整报告";
        case 2:
            return "预约实习指导";
        case 3:
            return "下载简历模板";
        default:
            return "了解更多";
    }
}

// 初始化滚动事件
function initScrollEvents() {
    const header = document.querySelector('.header');
    
    window.addEventListener('scroll', function() {
        if (window.scrollY > 100) {
            header.classList.add('scrolled');
        } else {
            header.classList.remove('scrolled');
        }
    });
}

// 初始化交互事件
function initInteractionEvents() {
    // 返回按钮
    const backButton = document.querySelector('.back-button');
    if (backButton) {
        backButton.addEventListener('click', function() {
            window.history.back();
        });
    }
    
    // 分享按钮
    const shareButton = document.querySelector('.share-button');
    const sharePanel = document.querySelector('.share-panel');
    const overlay = document.querySelector('.overlay');
    if (shareButton && sharePanel) {
        shareButton.addEventListener('click', function() {
            sharePanel.classList.add('show');
            overlay.classList.add('show');
        });
    }
    
    // 关闭分享面板
    const closeShare = document.querySelector('.close-share');
    if (closeShare) {
        closeShare.addEventListener('click', function() {
            sharePanel.classList.remove('show');
            overlay.classList.remove('show');
        });
    }
    
    // 评论按钮
    const commentBtn = document.querySelector('.comment-btn');
    const commentPanel = document.querySelector('.comment-panel');
    if (commentBtn && commentPanel) {
        commentBtn.addEventListener('click', function() {
            commentPanel.classList.add('show');
            overlay.classList.add('show');
        });
    }
    
    // 关闭评论面板
    const closeComments = document.querySelector('.close-comments');
    if (closeComments) {
        closeComments.addEventListener('click', function() {
            commentPanel.classList.remove('show');
            overlay.classList.remove('show');
        });
    }
    
    // 收藏按钮
    const likeBtn = document.querySelector('.like-btn');
    if (likeBtn) {
        likeBtn.addEventListener('click', function() {
            this.classList.toggle('active');
            const icon = this.querySelector('i');
            if (this.classList.contains('active')) {
                icon.className = 'bi bi-heart-fill';
                this.querySelector('span').textContent = '已收藏';
                showToast('收藏成功');
            } else {
                icon.className = 'bi bi-heart';
                this.querySelector('span').textContent = '收藏';
                showToast('已取消收藏');
            }
        });
    }
    
    // 主按钮
    const primaryButton = document.querySelector('.primary-button');
    if (primaryButton) {
        primaryButton.addEventListener('click', function() {
            const urlParams = new URLSearchParams(window.location.search);
            const id = urlParams.get('id');
            
            // 根据不同ID执行不同操作
            switch(id) {
                case "1":
                    window.location.href = "article-details.html?id=report1";
                    break;
                case "2":
                    showToast('预约申请已提交，请等待确认');
                    break;
                case "3":
                    showToast('简历模板下载中...');
                    setTimeout(() => {
                        window.location.href = "#"; // 这里可以是一个下载链接
                    }, 1500);
                    break;
                default:
                    window.location.href = "discover.html";
            }
        });
    }
    
    // 点击遮罩关闭所有面板
    if (overlay) {
        overlay.addEventListener('click', function() {
            sharePanel.classList.remove('show');
            commentPanel.classList.remove('show');
            this.classList.remove('show');
        });
    }
    
    // 发送评论按钮
    const sendComment = document.querySelector('.send-comment');
    const commentInput = document.querySelector('.comment-input');
    if (sendComment && commentInput) {
        sendComment.addEventListener('click', function() {
            const comment = commentInput.value.trim();
            if (comment) {
                // 模拟发送评论
                showToast('评论发送成功');
                commentInput.value = '';
                
                // 可以在这里添加评论到列表中
                addComment(comment);
            }
        });
    }
}

// 添加一条评论
function addComment(content) {
    const commentsContainer = document.querySelector('.comments-container');
    if (!commentsContainer) return;
    
    // 创建评论元素
    const commentElem = document.createElement('div');
    commentElem.className = 'comment-item';
    
    // 模拟用户信息
    const randomId = Math.floor(Math.random() * 100);
    
    commentElem.innerHTML = `
        <div class="comment-avatar">
            <img src="https://i.pravatar.cc/40?img=${randomId}" alt="用户头像">
        </div>
        <div class="comment-content">
            <div class="comment-user">
                <span class="user-name">用户${randomId}</span>
                <span class="comment-time">刚刚</span>
            </div>
            <p class="comment-text">${content}</p>
        </div>
    `;
    
    // 添加到容器顶部
    commentsContainer.insertBefore(commentElem, commentsContainer.firstChild);
    
    // 更新评论数
    const commentCount = document.querySelector('.comment-count');
    if (commentCount) {
        const currentCount = parseInt(commentCount.textContent);
        commentCount.textContent = currentCount + 1;
    }
}

// 初始化分享功能
function initShareFeature() {
    const shareOptions = document.querySelectorAll('.share-option');
    
    shareOptions.forEach(option => {
        option.addEventListener('click', function() {
            const type = this.querySelector('span').textContent;
            const url = window.location.href;
            const title = document.querySelector('.detail-title').textContent;
            
            showToast(`已分享到${type}`);
            
            if (type === '复制链接') {
                // 复制链接到剪贴板
                navigator.clipboard.writeText(url)
                    .then(() => {
                        showToast('链接已复制到剪贴板');
                    })
                    .catch(err => {
                        console.error('复制失败', err);
                        showToast('复制失败，请手动复制');
                    });
            }
            
            // 关闭分享面板
            document.querySelector('.share-panel').classList.remove('show');
            document.querySelector('.overlay').classList.remove('show');
        });
    });
}

// 显示/隐藏加载状态
function showLoading(show) {
    // 如果需要，可以添加一个加载指示器
    if (show) {
        document.querySelector('.detail-title').textContent = "加载中...";
        document.querySelector('.detail-description').textContent = "加载中...";
    }
}

// 显示错误信息
function showError(message) {
    document.querySelector('.detail-title').textContent = "出错了";
    document.querySelector('.detail-description').textContent = message;
}

// 处理图片加载错误
function handleImageErrors() {
    const images = document.querySelectorAll('img');
    
    images.forEach(img => {
        img.addEventListener('error', function() {
            // 根据图片所在容器类型设置不同的替代图
            let replacement = '';
            
            if (this.closest('.banner')) {
                replacement = `https://source.unsplash.com/random/800x400/?event&sig=${Math.random()}`;
            } else if (this.closest('.related-img')) {
                replacement = `https://source.unsplash.com/random/300x200/?career&sig=${Math.random()}`;
            } else {
                replacement = `https://source.unsplash.com/random/400x300/?business&sig=${Math.random()}`;
            }
            
            this.src = replacement;
        });
    });
}

// 显示Toast消息
function showToast(message) {
    // 如果页面中没有toast元素，则创建一个
    let toast = document.querySelector('.toast-message');
    if (!toast) {
        toast = document.createElement('div');
        toast.className = 'toast-message';
        document.body.appendChild(toast);
    }
    
    // 设置消息并显示
    toast.textContent = message;
    toast.classList.add('show');
    
    // 定时隐藏
    setTimeout(() => {
        toast.classList.remove('show');
    }, 2000);
}

// Toast样式
if (!document.getElementById('toast-style')) {
    const style = document.createElement('style');
    style.id = 'toast-style';
    style.innerHTML = `
        .toast-message {
            position: fixed;
            top: 60px;
            left: 50%;
            transform: translateX(-50%) translateY(-20px);
            background-color: rgba(0, 0, 0, 0.75);
            color: #fff;
            padding: 10px 20px;
            border-radius: 30px;
            font-size: 14px;
            z-index: 1000;
            opacity: 0;
            transition: all 0.3s ease;
            pointer-events: none;
            white-space: nowrap;
        }
        
        .toast-message.show {
            opacity: 1;
            transform: translateX(-50%) translateY(0);
        }
        
        .comment-item {
            display: flex;
            margin-bottom: 16px;
            animation: fadeIn 0.3s ease;
        }
        
        .comment-avatar {
            flex: 0 0 40px;
            height: 40px;
            border-radius: 50%;
            overflow: hidden;
            margin-right: 12px;
        }
        
        .comment-avatar img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        
        .comment-content {
            flex: 1;
        }
        
        .comment-user {
            display: flex;
            justify-content: space-between;
            margin-bottom: 4px;
        }
        
        .user-name {
            font-weight: 500;
            font-size: 14px;
        }
        
        .comment-time {
            font-size: 12px;
            color: #999;
        }
        
        .comment-text {
            font-size: 14px;
            line-height: 1.5;
            margin: 0;
        }
        
        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
    `;
    document.head.appendChild(style);
} 